<template>
  <div>
    <el-upload
      list-type="picture-card"
      action="#"
      :limit="1"
      :file-list="fileList"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :before-upload="handleBeforeUpload"
      :http-request="handleupload"
      :class="{disably:classShow}"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress
      v-if="progerssShow"
      :percentage="progerss"
      style="width: 180px"
    />
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'

var cos = new COS({
  SecretId: 'AKID4xbz7yYt1tUptgCSR9ajdGchW5NO9dqm', // 身份识别 ID
  SecretKey: 'g6F6g03pK6dtsa2D7k7C1YppY0B7nCKC' // 身份密钥
})
export default {
  name: 'Imges',
  data() {
    return {
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      // currentFileUid: null,
      progerss: 0,
      //   进度条是否显示
      progerssShow: false

    }
  },
  computed: {
    classShow() {
      return this.fileList.length === 1
    }
  },
  methods: {
    //   移除图片
    handleRemove(file, fileList) {
      this.fileList = this.fileList.filter(itm => itm.uid !== file.uid)
    },
    // 预览图片
    handlePreview(file) {
      console.log(file)
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 发送改变调用的钩子
    handleChange(file, fileList) {
      this.dialogImageUrl = file.url
      this.fileList = fileList
    },
    handleBeforeUpload(file) {
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(file.type)) {
        this.$message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
        return false
      }
      const maxSize = 10 * 1024 * 1024
      if (maxSize < file.size) {
        this.$message.error('图片大小最大不能超过5M')
        return false
      }
      // this.currentFileUid = file.uid
      this.progerssShow = true
      return true
    },
    // 自定义上传方式
    handleupload(data) {
      if (data.file) {
        cos.putObject({
          Bucket: 'renzixiangmu-1307703619',
          Region: 'ap-nanjing',
          Key: data.file.name,
          StorageClass: 'STANDARD',
          Body: data.file,
          onProgress: progressData => {
            this.progerss = progressData.percent * 100
          }
        }, (err, data) => {
          if (!err && data.statusCode === 200) {
            const reg = new RegExp(this.fileList[0].url, 'gi')
            this.fileList = JSON.parse(JSON.stringify(this.fileList).replace(reg, `http://${data.Location}`))
            this.fileList[0].onload = true
          }
        })
      }
      setTimeout(() => {
        this.progerssShow = false
        this.progerss = 0
      }, 2000)
    }
  }
}
</script>

<style>
.disably .el-upload--picture-card {
    display: none;
}
</style>
